import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

import '../../manager/app_manager.dart';
import '../../model/product.dart';

class HomeProductPanel extends ConsumerWidget {
  const HomeProductPanel({super.key});

  /// 添加商品
  void addProductAction() {
    AppManager.shared.addProduct();
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    print("HomeProductPanel build ...");
    final storeProducts = ref.watch(AppManager.shared.provider).storeProducts;
    //ref.watch(AppManager.shared.provider.select((value) => value.storeProducts));
    return MasonryGridView.count(
        crossAxisCount: 3,
        padding: const EdgeInsets.all(0),
        mainAxisSpacing: 0,
        crossAxisSpacing: 0,
        itemCount: storeProducts.length+1,
        shrinkWrap: true,
        itemBuilder: (context, index) {
          if (index < storeProducts.length) {
            Product product = storeProducts[index];
            return SizedBox(
              height: 35,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 3),
                child: Center(
                  child: AutoSizeText(
                    "${product.name}:${product.totalCount}-${product.saleCount}",
                    maxLines: 2,
                    style: const TextStyle(
                        fontSize: 15,
                        color: Colors.black
                    ),
                  ),
                ),
              ),
            );
          } else {
            return SizedBox(
              height: 35,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 3),
                child: Center(
                  child: IconButton(
                    icon: const Icon(
                      Icons.add_circle,
                      size: 20,
                    ),
                    onPressed: addProductAction,
                  ),
                ),
              ),
            );
          }
        }
    );
  }
}
